from api import models
from rest_framework.generics import CreateAPIView, ListAPIView, RetrieveAPIView
from api.authentication.auth import GeneralAuthentication
from api.serializer.news import NewsDetailModelSerializer, NewsModelSerializer, NewsDetailViewModel
from api.pagination.pages import MaxBaseFilterBackend, MinBaseFilterBackend, NewsListLimitOffsetPagination
from django.db.models import F


class NewsView(CreateAPIView, ListAPIView):
    serializer_class = [NewsDetailModelSerializer, NewsModelSerializer]
    queryset = models.News.objects.all().order_by("-id")
    pagination_class = NewsListLimitOffsetPagination
    filter_backends = [MinBaseFilterBackend, MaxBaseFilterBackend]

    # 通过CreateAPIView先执行perform_create调用sava方法通过create保存
    def perform_create(self, serializer):
        return serializer.save()

    def get_serializer_class(self):
        if self.request.method == "POST":
            return NewsDetailModelSerializer

        if self.request.method == "GET":
            return NewsModelSerializer


class NewsDetailView(RetrieveAPIView):
    queryset = models.News.objects
    serializer_class = NewsDetailViewModel
    authentication_classes = [GeneralAuthentication]

    def get(self, request, *args, **kwargs):
        response = super().get(request, *args, **kwargs)
        if not request.user:
            return response
        # 获取news对象
        news_object = self.get_object()
        exists = models.ViewerRecord.objects.filter(news=news_object, user=request.user).exists()
        if exists:
            return response
        models.ViewerRecord.objects.create(news=news_object, user=request.user)
        models.News.objects.filter(id=news_object.id).update(viewer_count=F('viewer_count') + 1)
        return response
